package com.xingfly.authentication;

import com.xingfly.authentication.annotation.Me;
import com.xingfly.constant.HttpConstant;
import com.xingfly.model.User;
import com.xingfly.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * Created by SuperS on 19/05/2017.
 * 通过注解注入用户
 *
 * @author SuperS
 */
@Component
public class CurrentUserResolvers implements HandlerMethodArgumentResolver {
    @Autowired
    private UserRepository userRepository;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //判断参数类型是否是User类并且参数上有Me注解。
        if (methodParameter.getParameterType().isAssignableFrom(User.class) &&
                methodParameter.hasParameterAnnotation(Me.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //通过认证拦截器设置在request请求中的id来获取user对象
        Long currentUserId = (Long) nativeWebRequest.getAttribute(HttpConstant.CURRENT_USER_ID, RequestAttributes.SCOPE_REQUEST);
        if (currentUserId != null) {
            // 从数据库中查询并返回
            return userRepository.findOne(currentUserId);
        }
        throw new MissingServletRequestPartException(HttpConstant.CURRENT_USER_ID);
    }
}
